import { reactControl, ReactViewState, ReactView, ReactViewControl } from "pao-aop-client";

import React from "react";

import { addon, Ref, getObject, log } from "pao-aop";
import { SignDetailLayout } from "src/projects/industryInternetSign/layout/sgin-detail-layout";
import { ISingleProductSignService, SingleProductSign, ProductSignCondition } from "src/models/singleProductSign";
import SignFrameLayout, { InputType } from "src/business/style-components/sign-frame-layout";
import { NTOperationTable } from "src/business/components/operation-table";
import { match } from "react-router";
import { ColumnConfig } from "src/business/components/detail";
import { IProductTypeService } from "src/models/productType";
import { change_structure, SIGN_ID, ROUTE_PATH, isPermission } from "../../app/util-tool";
import { message } from "antd";
import { PermissionList } from "../../app/permission";

/**
 * 组件：单品标识详情视图控件状态
 */
export interface SingleProductDetailState extends ReactViewState {
    /** 单品标识数据源 */
    data?: SingleProductSign | any;
    /** 品类标识列表数据源 */
    data_source?: any[];
    /** 当前第几页 */
    page?: number;
    /** 当前每页数 */
    pageSize?: number;
    /** 数据总条数 */
    total_data?: number;
    /** 查询条件对象 */
    condition?: ProductSignCondition;
    /** 产品类型列表 */
    product_data?: any;
    /** 滚动条 */
    loading?: boolean;
}

/**
 * 组件：单品标识详情视图控件
 * 描述
 */
export class SingleProductDetail extends ReactView<SingleProductDetailViewControl, SingleProductDetailState> {
    columns_data_source = [{
        title: '品类名称',
        dataIndex: 'handle_name',
        key: 'handle_name',
        width: 500,
    }, {
        title: '产品类型',
        dataIndex: 'product_type',
        key: 'product_type',
        width: 150,
        render: (text: string, record: any, index: any) => {
            let product = this.state.product_data;
            if (text && product) {
                return product.get(text) ? product.get(text) : text;
            }
        }
    }, {
        title: '品类标识',
        dataIndex: 'handle_code',
        key: 'handle_code',
        width: 500,
    }, {
        title: '创建时间',
        dataIndex: 'create_date',
        key: 'create_date',
        width: 150,
    }];
    constructor(props: SingleProductDetailViewControl) {
        super(props);
        this.state = {
            page: 1,
            pageSize: 10,
            loading: false,
            data: new SingleProductSign()
        };
    }
    /** 分页回调事件 */
    pageOnCick = (contents: any) => {
        console.log('page:', contents);
        this.setState({
            page: contents,
            loading: true
        });
        this.queryList(this.state.condition ? this.state.condition! : {}, contents, this.state.pageSize!)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("singleProductDetailViewControl", error.message);
            });
    }
    /** 改变分页数量回调事件 */
    showSizeChange = (current: number, pageSize: number) => {
        console.log('current: ' + current + 'pageSize: ' + pageSize);
        this.setState({
            pageSize: pageSize,
            loading: true
        });
        this.queryList(this.state.condition ? this.state.condition! : {}, 1, pageSize)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("singleProductDetailViewControl", error.message);
            });
    }
    /** 修改Icon回调事件 */
    onClickEditor = () => {
        this.props.history!.push(ROUTE_PATH.changeSingleProductView + `/${this.state.data!.id}`);
    }
    /** 删除Icon回调事件 */
    onClickDel = () => {
        this.setState({
            loading: true
        });
        this.deleteDeatail()
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("SingleProductDetailViewControl-delete", error.message);
            });
    }
    // 查询回调
    private search = (e: any, val: ProductSignCondition) => {
        // 带上单品标识id
        val.id = this.state.condition!.id;
        this.setState({
            condition: val,
            loading: true
        });
        this.queryList(val, 1, this.state.pageSize ? this.state.pageSize : 10)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("SingleProductDetailViewControl", error.message);
            });
    }
    // 重置回调
    private reset = () => {
        console.log("重置回调");
        this.setState({
            condition: {}
        });
    }
    componentWillMount() {

    }
    componentDidMount() {
        this.setState({
            loading: true
        });
        this.queryData()
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("SingleProductDetailViewControl", error.message);
            });
    }
    // 初始化产品类型服务
    productTypeService?() {
        return getObject(this.props.productTypeService_Fac!);
    }
    // 初始化服务
    singleProductSignService?() {
        return getObject(this.props.singleProductSignService_Fac!);
    }
    // 查询表格列表信息
    async queryList(condition: ProductSignCondition, page: number, count: number) {
        const data_list = await this.singleProductSignService!()!.get_category_list!(condition, page, count)!;
        this.setState({
            data_source: data_list ? data_list!.result : []
        });
    }
    // 删除单品详情信息
    async deleteDeatail() {
        let { [SIGN_ID]: id } = this.props.match!.params;
        const result = await this.singleProductSignService!()!.delete_single!([id])!;
        message.info("删除" + (result ? '成功' : '失败'));
        if (result) {
            this.props.history!.push(ROUTE_PATH.singleProductView);
        }
    }
    // 查询详情信息
    async queryData() {
        let { [SIGN_ID]: id } = this.props.match!.params;
        const data = await this.singleProductSignService!()!.get_single!(id)!;
        let condition: ProductSignCondition = {};
        condition.id = data ? data!.id : '';
        const data_list = await this.singleProductSignService!()!.get_category_list!(condition, this.state.page ? this.state.page : 1, this.state.pageSize ? this.state.pageSize : 10)!;
        const product_data = await this.productTypeService!()!.get_product_type_list!()!;
        let product_map = change_structure('product_type_name', product_data!.result);
        /** 把产品类型转成中文 */
        if (data && data.product_type) {
            let key = data.product_type;
            data.product_type = product_map.get(key) ? product_map.get(key) : key;
        }
        this.setState({
            condition: condition,
            data: data,
            total_data: data_list ? data_list!.total : 0,
            data_source: data_list ? data_list!.result : [],
            product_data: product_map
        });
    }
    render() {
        const redeirect = isPermission ? isPermission!(PermissionList.SingleProduct_Select) : undefined;
        if (redeirect) {
            return redeirect;
        }
        let { data } = this.state;
        let title_detail_columns: ColumnConfig[] = [
            { title: '单品标识:', fieldName: 'handle_code' },
            { title: '产品类型:', fieldName: 'product_type' },
            { title: '创建日期:', fieldName: 'create_date' },
        ];

        if (data && data.custom_attribute) {
            for (let i = 0; i < data.custom_attribute.length; i++) {
                title_detail_columns.push({
                    title: data.custom_attribute[i].label! + ': ', // + (data.custom_attribute[i].value instanceof Array ? '' : data.custom_attribute[i].value!),
                    fieldName: 'custom_attribute' + i, // data.custom_attribute[i].value!,
                    type: data.custom_attribute[i].value instanceof Array ? 'img' : undefined
                });
                data['custom_attribute' + i] = data.custom_attribute[i].value!;
            }
        }
        let category_model_props = {
            edit_form_items_props: [{
                type: InputType.input,
                label: "品类模板名称",
                decorator_id: "handle_name",
                default_value: "",
                option: {
                    placeholder: "请输入品类模板名称"
                }
            },
            {
                type: InputType.input,
                label: "品类模板标识",
                decorator_id: "handle_code",
                default_value: "",
                option: {
                    placeholder: "请输入品类模板标识"
                }
            },
            {
                type: InputType.date,
                label: "创建时间",
                decorator_id: "create_date",
                default_value: ""
            }],
            showTable: (
                <NTOperationTable
                    data_source={this.state.data_source}
                    columns_data_source={this.columns_data_source}
                    table_size='middle'
                    showHeader={true}
                    bordered={false}
                    total={this.state.total_data ? this.state.total_data : 0}
                    total_pages={Math.ceil((this.state.total_data ? this.state.total_data : 1) / 10)}
                    default_page_size={10}
                    show_footer={true}
                    page_on_click={this.pageOnCick}
                    show_size_change={this.showSizeChange}
                    rowKey='id'
                />),
            search_cb: this.search,
            reset_cb: this.reset
        };
        let this_props = {
            loading: this.state.loading,
            title_name: this.state.data!.handle_name,
            rc_code: this.state.data!.rc_code,
            title_detail_columns: title_detail_columns,
            title_detail_columns_data: data,
            icon_props: [{
                icon: 'antd@edit',
                btn_method: this.onClickEditor
            }, {
                icon: 'antd@delete',
                btn_method: this.onClickDel
            }],
            picture: { title_name: '单品图片', picture_data: this.state.data!.product_picture },
            tab: [{
                name: '已引用的品类模板标识',
                showElement: (
                    <SignFrameLayout {...category_model_props} />
                )
            }]
        };
        return (
            <SignDetailLayout {...this_props} />
        );
    }
}

/**
 * 控件：单品标识详情视图控件
 * 控制单品标识详情视图控件
 */
@addon('SingleProductDetail', '单品标识详情视图控件', '控制单品标识详情视图控件')
@reactControl(SingleProductDetail, true)
export class SingleProductDetailViewControl extends ReactViewControl {
    /**
     * 单品标识服务
     */
    public singleProductSignService_Fac?: Ref<ISingleProductSignService>;
    /** 
     * 产品类型服务
     */
    public productTypeService_Fac?: Ref<IProductTypeService>;
    match?: match<{ [SIGN_ID]: string }>;
}